package com.dcjt.firehotcarpad.fragment

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProviders
import com.amap.api.maps.model.LatLng
import com.aries.library.fast.module.fragment.FastRefreshLoadFragment
import com.aries.library.fast.retrofit.FastObserver
import com.aries.library.fast.util.FastStackUtil
import com.aries.library.fast.util.FastUtil
import com.aries.library.fast.util.SPUtil
import com.aries.library.fast.util.ToastUtil
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.dcjt.firecommand.manager.MapDataRec
import com.dcjt.firehotcarpad.R
import com.dcjt.firehotcarpad.base.ApiPath
import com.dcjt.firehotcarpad.base.BaseViewModelEntity
import com.dcjt.firehotcarpad.base.SPConstant
import com.dcjt.firehotcarpad.entity.BaseListEntity
import com.dcjt.firehotcarpad.entity.EventEntity
import com.dcjt.firehotcarpad.entity.MapEvent
import com.dcjt.firehotcarpad.helper.CountDownDialogHelper
import com.dcjt.firehotcarpad.manager.DataManager
import com.dcjt.firehotcarpad.manager.TtsManager
import com.dcjt.firehotcarpad.model.HandleDisasterViewModel
import com.dcjt.firehotcarpad.moudle.CarConfigActivity
import com.dcjt.firehotcarpad.moudle.HandleDisasterActivity
import com.dcjt.firehotcarpad.moudle.NavActivity
import com.dcjt.firehotcarpad.retrofit1.repository.ApiRepository1
import com.dcjt.firehotcarpad.utils.AlertDialogUtil
import com.dcjt.firehotcarpad.utils.LocationType
import com.dcjt.firehotcarpad.utils.MarkerToMapType
import com.dcjt.firehotcarpad.utils.StringUtils
import com.google.gson.annotations.SerializedName
import kotlinx.android.synthetic.main.activity_login.*

/**
 * Created by cj on 2021/2/22.
 * Email:codesexy@163.com
 * Function:
 * desc:新版本的警情列表
 */
class DisastersListFragment : FastRefreshLoadFragment<DisasterListInfoEntity>(),NewMessagePool.NewMessageObserverObserver {

    companion object {
        fun newInstance(): DisastersListFragment {
            var fragment = DisastersListFragment()
            return fragment
        }
    }
    lateinit var viewModel_detail: HandleDisasterViewModel
     private var currentPage: Int = 0
    private lateinit var mAdapter: DisatstersListAdapter
    private lateinit var mViewModel: DisasterListViewModel
    override fun getContentLayout(): Int = R.layout.fast_layout_multi_status_refresh_recycler

    override fun initView(savedInstanceState: Bundle?) {
        mViewModel = ViewModelProviders.of(this).get(DisasterListViewModel::class.java)
        NewMessagePool.get().registerNewMessageObserver(this)
        mViewModel.listData.observe(
            this,
            Observer<BaseViewModelEntity<List<DisasterListInfoEntity>>> { entity ->
                mEasyStatusView.content()
                if (entity.isSuccess) {
                    val data = entity.data
                    if (data == null || data.isEmpty()) {
//                        if (0 == DEFAULT_PAGE && mAdapter.data.size == 0) { //第一页就么有
                        if (0 == DEFAULT_PAGE) { //第一页就么有
                            mEasyStatusView.empty()
                        } else {
                            mAdapter.loadMoreEnd()
                        }
                        return@Observer
                    }
                    mAdapter.loadMoreComplete()

                    if (mRefreshLayout.isRefreshing && DEFAULT_PAGE === 0) {
                        mAdapter.setNewData(ArrayList())
                        mRefreshLayout.finishRefresh()
                    }

                    mAdapter.addData(data)
                    MapOperationEventPool.get().sendDisasterMakersDispatch(mAdapter.data, MarkerToMapType.MARKER_ADD,currentPage)

                    if (data.size < DEFAULT_PAGE_SIZE) {
                        mAdapter.loadMoreEnd()
                    }

                } else {//失败
                    if (mRefreshLayout.isRefreshing) {
                        mRefreshLayout.finishRefresh();
                    } else {
                        if (mAdapter.data.size == 0) {
                            mEasyStatusView.error();
                        }
                    }
                }

            })
    }

    override fun loadData(page: Int) {
        mViewModel.loadData(page)
        currentPage = page
    }

    override fun getAdapter(): BaseQuickAdapter<DisasterListInfoEntity, BaseViewHolder> =
        DisatstersListAdapter(null).apply { mAdapter = this }

    override fun onItemClicked(
        adapter: BaseQuickAdapter<DisasterListInfoEntity, BaseViewHolder>?,
        view: View?,
        position: Int
    ) {
        super.onItemClicked(adapter, view, position)
        adapter?.getItem(position)?.id?.let {
            startActivityForResult(
                Intent( mContext, HandleDisasterActivity::class.java).putExtra("jqid",it), ApiPath.REQUEST_CODE
            )

        }
    }

    override fun onDestroy() {
        super.onDestroy()
        NewMessagePool.get().unRegisterNewMessageObserver(this)

    }

    override fun onNewDisasterMessage(data: EventEntity.MessageDetailEvent) {
        super.onNewDisasterMessage(data)
        //当前页面的时候  才显示
        if (requireActivity().javaClass == FastStackUtil.getInstance().current.javaClass) {
            startActivityForResult(
                Intent( mContext, HandleDisasterActivity::class.java).putExtra("jqid",data.zqId), ApiPath.REQUEST_CODE
            )
        }
    }

    override fun onCarLocationChange(data: EventEntity.MessageDetailEvent) {
        //跳转页面
        //当前页面的时候  才显示
        if (requireActivity().javaClass == FastStackUtil.getInstance().current.javaClass) {
            //作战位改变  直接跳转导航页面
            if (!StringUtils.isEmpty(data.carY.toString()))
                NavActivity.startNavActivity(FastStackUtil.getInstance().current,data.carY, data.carX)
        }

    }

    override fun onRefreshList() {
        super.onRefreshList()
        mRefreshLayout.autoRefresh()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == ApiPath.REQUEST_CODE /*&& resultCode == ApiPath.RESULT_CODE*/){
            mRefreshLayout.autoRefresh()
        }
    }

}

// viewModel
class DisasterListViewModel : ViewModel() {

    var listData: MutableLiveData<BaseViewModelEntity<List<DisasterListInfoEntity>>> =
        MutableLiveData()

    fun loadData(page: Int) {
        // FIXME: 2021/2/22 需要更换成车辆的id
        ApiRepository1.getInstance().getDisasterList(DataManager.getInstance().user.account, page)
            .subscribe(object : FastObserver<BaseListEntity<DisasterListInfoEntity>>() {
                override fun _onNext(entity: BaseListEntity<DisasterListInfoEntity>) {
                    listData.postValue(BaseViewModelEntity(entity.records, true))
                }

                override fun _onError(errorRes: Int, errorCode: Int, e: Throwable) {
                    super._onError(errorRes, errorCode, e)
                    listData.postValue(BaseViewModelEntity(isSuccess = false))
                }
            })
    }


}

// 消息实体
data class DisasterListInfoEntity(
    @SerializedName("ajdjbh") val ajdjbh: String?,
    @SerializedName("ajdjmc") val ajdjmc: String?,
    @SerializedName("ajlx") val ajlx: String?,
    @SerializedName("ajlxmc") val ajlxmc: String?,
    @SerializedName("ajztbh") val ajztbh: String?,
    @SerializedName("ajztmc") val ajztmc: String?,
    @SerializedName("bjsj") val bjsj: String?,
    @SerializedName("gis_x") val gisX: String?,
    @SerializedName("gis_y") val gisY: String?,
    @SerializedName("id") val id: String?,
    @SerializedName("lasj") val lasj: String?,
    @SerializedName("lxdh") val lxdh: String?,
    @SerializedName("sfdz") val sfdz: String?,
    @SerializedName("xzqdm") val xzqdm: String?,
    @SerializedName("xzqmc") val xzqmc: String?,
    @SerializedName("zgdw") val zgdw: String?
)


// adapter
class DisatstersListAdapter(data: List<DisasterListInfoEntity>?) :
    BaseQuickAdapter<DisasterListInfoEntity, BaseViewHolder>(
        R.layout.item_layout_disaster_list,
        data
    ) {

    override fun convert(helper: BaseViewHolder?, item: DisasterListInfoEntity?) {
        helper!!
        item!!
        helper.setText(R.id.tv_name, "${item.sfdz}")
            .setText(R.id.tv_address, "${item.xzqmc}${item.ajdjmc}${item.ajlxmc}")
            .setText(R.id.tv_time, "${item.lasj}")
            .setText(R.id.rtv_zt,"${item.ajztmc}")
            .setImageResource(R.id.iv_icon,MapDataRec.getCaseIcon(item.ajlx))
    }

}